package com.oocl.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.pojo.Customer;
import com.oocl.service.CustomerManager;
import com.oocl.service.impl.CustomerManagerFactory;

/**
 * Servlet implementation class UpdateCustomerServlet
 */
public class UpdateCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerManager manager;
    
    public UpdateCustomerServlet() {
        super();
        manager = CustomerManagerFactory.getInstance();
    }
 

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("test/html;charset=utf-8");
		
		String cid = request.getParameter("id");
		String cname = request.getParameter("cname");
		System.out.println(cname);
		String csex = request.getParameter("sex");
		String csal = request.getParameter("salary");
		String cbirth = request.getParameter("birthDate");
		String[] chobby = request.getParameterValues("hobby");
		
		int id = 0;
		try {
			id = Integer.parseInt(cid);
		} catch (NumberFormatException e2) {
			sendError("更新时id不能为空或者id只能是数字",request,response);
			return;
		}
		if(null==cname || "".equals(cname)){
			sendError("用户名不能为空",request,response);
			return;
		}
		
		boolean sex = Boolean.parseBoolean(csex);
		double sal = 0;
		if(null!=csal && !"".equals(csal)){
			try {
				sal = Double.parseDouble(csal);
			} catch (NumberFormatException e1) {
				sendError("工资必须为数字",request,response);
				return;
			}
		}
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date birth = null;
		if(null!=cbirth && !"".equals(cbirth)){
			try {
				 birth = format.parse(cbirth);
			} catch (ParseException e) {
				sendError("生日格式有误",request,response);
				return;
			}
		}
		
		Customer customer = new Customer(id, cname, sex, sal, birth, chobby);
		int m = manager.updateCustomer(customer);
		if(m>0){
			request.getSession().setAttribute("result", "更新成功");
		}else {
			request.getSession().setAttribute("result", "更新失败");
		}
		response.sendRedirect("result.jsp");
		System.out.println(customer);
	}
	
	private void sendError(String msg, HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		request.getSession().setAttribute("error", msg);
		response.sendRedirect("update.jsp");
	}

}
